package com.xsprite.managesys.servlet.gm;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.mina.core.session.IoSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.game.GMClientServer;
import com.game.gm.config.GMComm;
import com.game.gm.handler.ResGMmsgHandler;
import com.game.gm.load.GMCommLoad;
import com.game.gm.manager.GMManager;
import com.xsprite.managesys.servlet.BaseServlet;

/**
 * Servlet implementation class ChangeNoticeServlet
 */
public class ChangeNoticeServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.service(req, resp);
		try {
			com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(queryParam("paras"));
			if (checkParas(jsonObj)) {
				ResGMmsgHandler handler = new ResGMmsgHandler();
				handler.setUserid(getReq().getSession().getAttribute("userid").toString());
				handler.setGmNo(28);
				changeNotice(jsonObj, handler);
				while (!handler.isFinish()) {
					Thread.sleep(500);
				}
			}
		} catch (Exception ex) {
			getResp().getWriter().print(ex.getMessage());
			ex.printStackTrace();
		}
	}

	private void changeNotice(JSONObject jsonObject, ResGMmsgHandler handler) throws IOException {
		String command = makeCommand(jsonObject);
		JSONArray serversArray = jsonObject.getJSONArray("servers");
		JSONObject serverObj = (JSONObject) serversArray.get(0);
		String tag = serverObj.getString("tag");
		
		IoSession session = GMClientServer.getInstance().createSession(tag, getResp().getWriter(), handler);
		GMManager.getInstance().sendGMmsg(session, command);
	}

	private String makeCommand(JSONObject jsonObject) {
		GMComm gmComm = (GMComm) GMCommLoad.getInstance().getGmComms().get(Integer.valueOf(28));

		StringBuffer sendBuf = new StringBuffer();
		sendBuf.append(gmComm.getGmComm());
		return sendBuf.toString();
	}

	private boolean checkParas(JSONObject jsonObject) throws IOException {
		JSONArray serversArray = jsonObject.getJSONArray("servers");
		if (serversArray.size() < 1) {
			getResp().getWriter().print("服务器不能为空");
			return false;
		}
		return true;
	}
}
